package com.example.service.impl;

import com.example.DAO.GoodDAO;
import com.example.service.GoodService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.example.entity.Goods;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

@Service
public class GoodServiceImpl implements GoodService {
    @Resource
    GoodDAO goodDAO;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public PageInfo<Goods> queryAll(Integer pagenum, Integer pagesize) {
        PageHelper.startPage(pagenum,pagesize);
        ArrayList<Goods> goodsList = goodDAO.queryAll();
        PageInfo<Goods> pageInfo = new PageInfo<>(goodsList);
        return pageInfo;
    }

    // @CacheEvict(cacheNames = "goods")
    @Override
    public int deletebyid(Integer id) {
        int count = goodDAO.deletebyid(id);
        redisTemplate.delete("goods_"+id);
        return count;
    }

    //@Cacheable(cacheNames = "goods")
    @Override
    public Goods findbyid(Integer id) {
        boolean flag = redisTemplate.hasKey("goods_"+id);
        if(flag) {
            Object obj = redisTemplate.opsForValue().get("goods_" + id);
            if (obj != null) {
                return (Goods) obj;
            }
        }

        Goods goods = goodDAO.findbyid(id);
        redisTemplate.opsForValue().set("goods_"+id,goods,1, TimeUnit.HOURS);
        return goods;
    }

    // @CachePut(cacheNames = "goods")
    @Override
    public int updatebyid(Goods goods) {
        int count = goodDAO.updatebyid(goods);
        redisTemplate.opsForValue().set("goods_"+goods.getGdid(),goods);
        return count;
    }

    // @CachePut(cacheNames = "goods")
    @Override
    public int insert(Goods goods) {
        return goodDAO.insert(goods);
    }

}


